import { _decorator, Component, resources, SpriteFrame, ImageAsset, Texture2D, assetManager, Asset } from 'cc';
const { ccclass, property } = _decorator;

/**
 * UI资源管理器
 * 负责管理所有UI资源的加载和缓存
 */
@ccclass('UIManager')
export class UIManager extends Component {
    private static _instance: UIManager = null;
    
    public static get instance(): UIManager {
        return this._instance;
    }
    
    private _uiCache: Map<string, SpriteFrame> = new Map();
    private _loadingPromises: Map<string, Promise<SpriteFrame>> = new Map();
    
    onLoad() {
        if (UIManager._instance === null) {
            UIManager._instance = this;
        } else {
            this.node.destroy();
        }
    }
    
    /**
     * 加载UI资源
     * @param path 资源路径
     * @returns Promise<SpriteFrame>
     */
    public loadUI(path: string): Promise<SpriteFrame> {
        // 检查缓存
        if (this._uiCache.has(path)) {
            return Promise.resolve(this._uiCache.get(path));
        }
        
        // 检查是否正在加载
        if (this._loadingPromises.has(path)) {
            return this._loadingPromises.get(path);
        }
        
        // 创建新的加载Promise
        const promise = new Promise<SpriteFrame>((resolve, reject) => {
            resources.load(path, SpriteFrame, (err, spriteFrame) => {
                if (err) {
                    console.error(`加载UI资源失败: ${path}`, err);
                    reject(err);
                    return;
                }
                
                this._uiCache.set(path, spriteFrame);
                this._loadingPromises.delete(path);
                resolve(spriteFrame);
            });
        });
        
        this._loadingPromises.set(path, promise);
        return promise;
    }
    
    /**
     * 预加载UI资源
     * @param paths 资源路径数组
     * @returns Promise<void>
     */
    public preloadUI(paths: string[]): Promise<void> {
        const promises = paths.map(path => this.loadUI(path));
        return Promise.all(promises).then(() => {});
    }
    
    /**
     * 释放UI资源
     * @param path 资源路径
     */
    public releaseUI(path: string): void {
        if (this._uiCache.has(path)) {
            const spriteFrame = this._uiCache.get(path);
            assetManager.releaseAsset(spriteFrame);
            this._uiCache.delete(path);
        }
    }
    
    /**
     * 释放所有UI资源
     */
    public releaseAllUI(): void {
        this._uiCache.forEach((spriteFrame, path) => {
            assetManager.releaseAsset(spriteFrame);
        });
        this._uiCache.clear();
    }
    
    /**
     * 获取UI资源
     * @param path 资源路径
     * @returns SpriteFrame | null
     */
    public getUI(path: string): SpriteFrame | null {
        return this._uiCache.get(path) || null;
    }
    
    /**
     * 检查UI资源是否已加载
     * @param path 资源路径
     * @returns boolean
     */
    public hasUI(path: string): boolean {
        return this._uiCache.has(path);
    }
    
    onDestroy() {
        this.releaseAllUI();
    }
} 